﻿using OmronFinsUDP;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    public partial class Form_Alarm : Form
    {

        private BackgroundWorker bgWorker = new BackgroundWorker();
        public bool connectFlag = false;
        public string[] pingOKList = new string[255];
        int pingOKListNum = 0;
        public bool[] connectPing = new bool[256];//= { false, false, false, false, false, false };
        EtherNetPLCUDP ENT_02 = new EtherNetPLCUDP();
        public Form_Alarm()
        {
            InitializeComponent();
            InitializeBackgroundWorker();
        }
        private void InitializeBackgroundWorker()//后台进程初始化
        {
            bgWorker.WorkerReportsProgress = true;
            bgWorker.WorkerSupportsCancellation = true;
            bgWorker.DoWork += new DoWorkEventHandler(bgWorker_DoWork);
            bgWorker.ProgressChanged += new ProgressChangedEventHandler(bgWorker_ProgessChanged);
            bgWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgWorker_WorkerCompleted);
        }
        public void bgWorker_DoWork(object sender, DoWorkEventArgs e)//后台进程
        {
            int pingL = 0;
            for (int i = 0; i >= 0;)
            {
                if (bgWorker.CancellationPending)
                {
                    e.Cancel = true;
                    return;
                }
                else
                {
                    bgWorker.ReportProgress(i, "Working");
                    System.Threading.Thread.Sleep(500);
                    if (connectFlag)
                    {
                    }
                }
                if (pingL == 0)//延时PING
                {
                    ping_PLC_ip();
                }
                pingL++;
                if (pingL > 1)//循环50次后再ping
                {
                    pingL = 0;
                }
            }
        }
        public void bgWorker_ProgessChanged(object sender, ProgressChangedEventArgs e)//后台进程更新界面
        {
            //——————ping 动作

            label_PingRe.Text = "";

            for (int i = 0; i < pingOKList.Length; i++)
            {
                if (pingOKList[i] == null)
                {
                    if (label4.Text == "ping")
                    {
                        label4.Text = "未ping到,下拉框↑中默认显示所有IP";
                    }
                    break;
                }
                else
                {
                    if (label4.Text != "ping到IP在下拉框中↑")
                    {
                        comboBox1.Text = pingOKList[0];
                        label6.Visible = false;
                    }
                    label4.Text = "ping到IP在下拉框中↑";
                    comboBox1.Items.Clear();
                    for (int j = 0; j < pingOKList.Length; j++)
                        if (pingOKList[j] != null)

                            comboBox1.Items.Add(pingOKList[j]);


                    label_PingRe.Text = (label_PingRe.Text + pingOKList[i] + "\r\n");
                }
            }

        }
        public void bgWorker_WorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                MessageBox.Show(e.Error.ToString());
                return;
            }

        }
        private void ping_PLC_ip()
        {
            string name = Dns.GetHostName();
            IPAddress[] iplist = Dns.GetHostAddresses(name);
            bool PLConline = false;
            Ping ping = new Ping();
            String[] ip = { "", "", "", "", "", "" };
            string okip = "127.0.0.0";
            PingReply pingReply;
            string test01;


            for (int j = 0; j < iplist.Length; j++)
            {
                if (iplist[j].AddressFamily == AddressFamily.InterNetwork)//单ip地址为IPV4时开始ping
                {

                    okip = Int2IP(iplist[j].Address, 3);//取当前IP地址前3个数值
                    if (okip == "192.168.10.")
                    {
                        //开始PING 130-150共20个地址
                        pingOKListNum = 0;
                        for (int i = 0; i < 10; i++)
                        {
                            connectPing[i] = false;
                            try
                            {
                                test01 = okip + (i + 130).ToString();
                                pingReply = ping.Send((test01), timeout: 120);

                                if (pingReply.Status == IPStatus.Success)
                                {
                                    connectPing[i] = true;
                                    pingOKList[pingOKListNum] = test01;
                                    pingOKListNum++;
                                }

                                else

                                    connectPing[i] = false;
                            }
                            catch (Exception)

                            {
                                break;
                                //throw;

                            }
                        }
                    }


                }
            }


        }
        public static string Int2IP(long intIP, int num)
        {
            StringBuilder sbd1 = new StringBuilder();
            if (num >= 1)
            {
                sbd1.Append(intIP & 0xff).Append(".");
                if (num >= 2)
                {
                    sbd1.Append((intIP >> 8) & 0xff).Append(".");
                    if (num >= 3)
                    {
                        sbd1.Append((intIP >> 16) & 0xff).Append(".");
                        if (num >= 4)
                        {
                            sbd1.Append((intIP >> 24) & 0xff);

                        }
                    }
                }
            }
            return sbd1.ToString();
        }
        private void Form3_Load(object sender, EventArgs e)
        {
            bgWorker.RunWorkerAsync("hello");

        }
        bool connectOK = false;
        //建立连接
        private void button1_Click_1(object sender, EventArgs e)
        {
            if (button_connect.Text == "建立连接")
            {

                if (connectOK)
                {
                    button_connect.Text = "断开连接";
                }
                else
                {
                    button_connect.Text = "连接失败";
                }
            }
            else
            {
                ;
            }
        }
        //发送
        private void button2send_Click(object sender, EventArgs e)
        {
            connectOK = ENT_02.Link("192.168.10.131", 9600);
            richTextBox1.Text = "";

            Byte[] rd ;
            ENT_02.ReadBytes(EtherNetPLCUDP.PlcMemoryType.DM, 1300,8 , out rd);



            for (int i = 0; i < rd.Length; i++)
            {
                richTextBox1.Text = richTextBox1.Text + "\r\n" + rd[i].ToString();

            }


        }
        //接收
        private void button3_Click(object sender, EventArgs e)
        {
            try
            {
                string 发送内容 = "发送内容";
                UdpClient udpclient = new UdpClient();
                IPEndPoint iPEndPoint = new IPEndPoint(IPAddress.Parse("192.168.10.222"), 8080);
                byte[] data = Encoding.Default.GetBytes(发送内容);
                //udpclient.Send(data, data.Length, iPEndPoint);
                string string1 = udpclient.ReceiveAsync().ToString() ;
                //data=udpclient.Receive(ref iPEndPoint);
                    //（data, data.Length, iPEndPoint);
                udpclient.Close();
                richTextBox1.Text = string1;
            }
            catch (Exception ex)
            {
                MessageBox.Show("UDP发送数据" + ex.ToString());
                throw;
            }
        
        }
        private void Form_Alarm_Load(object sender, EventArgs e)
        {

        }
    }
}
